package com.tmt.paymentcenter.web.controller;

import com.tmt.helper.DateHelper;
import com.tmt.paymentcenter.web.service.BaseComponent;
import com.tmt.paymentcenter.web.vo.Notify;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.*;

/**
 * 基础组件
 * Created by Stark on 2017/3/2.
 */
@Component
public class BaseController extends BaseComponent {

	public static final String NOTIFY = "__NOTIFY";

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new DateEditor(DateHelper.DATE_TIME_FORMAT));
	}

	/**
	 * 往前台发送通知。适用于初始页面显示
	 *
	 * @param model  模型
	 * @param notify 通知
	 */
	protected void notify(Model model, Notify notify) {
		Objects.requireNonNull(model, "model can't be null.");
		Objects.requireNonNull(model, "notify can't be null.");

		Optional<List<Notify>> o = Optional.ofNullable((List<Notify>) model.asMap().get(NOTIFY));
		List<Notify> list = o.orElse(new ArrayList<>());
		list.add(notify);

		model.addAttribute(NOTIFY, list);
	}


	public static class DateEditor extends PropertyEditorSupport {
		private final String formatPattern;

		public DateEditor(String formatPattern) {
			this.formatPattern = formatPattern;
		}

		@Override
		public void setAsText(String text) {
			if (!StringUtils.hasText(text)) {
				setValue(null);
			} else {
				setValue(DateHelper.parseDate(text));
			}
		}

		/**
		 * Format the Date as String, using the specified DateFormat.
		 */
		@Override
		public String getAsText() {
			Date value = (Date) getValue();
			return (value != null ? DateHelper.formatDate(value, formatPattern) : "");
		}
	}
}
